//
//  ReadAppUptadaManager.m
//  LiteraryTune
//
//  Created by mack on 2018/11/18.
//  Copyright © 2018 cxd. All rights reserved.
//

#import "ReadAppUptadaManager.h"
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

@implementation ReadAppUptadaManager
+ (instancetype)sharedInstance {
    static ReadAppUptadaManager *sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
/**
 *  初始化信息配置
 */
- (void)configureApp{
    
    [self getWhiteVerdionList];
    
}

/**
 *  懒加载
 */
- (NRWAppInfoModel *)versionInfo{
    if (!_versionInfo) {
        _versionInfo = [NRWAppInfoModel new];
    }
    return _versionInfo;
}
/**
 *  向自己的后台请求白名单信息
 */
- (void)getWhiteVerdionList {
//    [self.updataApi start];
    NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
    
    [CXDNetHelp getRequestWithURLString:@"http://service.wenqujingdian.com/wqjd/app/GetTheCurrentVersionOfApp" parameters:@{@"appId":@"ios",@"appType":@"ios"} success:^(id  _Nullable responseObject) {
        if ([responseObject[@"result"] integerValue] == 1) {
            if ([responseObject[@"data"][@"gradleVersion"] floatValue] < [currentVersion floatValue]) {
                if ([responseObject[@"data"][@"isForced"] integerValue] == 1) {
                    
                    [ReadAppUptadaManager sharedInstance].needsForceUpdate = YES;
                    
                }else{
                    [ReadAppUptadaManager sharedInstance].needsForceUpdate = NO;
                }
            }
            if ([responseObject[@"data"][@"needLogin"] integerValue] == 0) {
                [NSUserDefaults.standardUserDefaults setBool:NO forKey:K_NeedLogin];
            } else {
                [NSUserDefaults.standardUserDefaults setBool:YES forKey:K_NeedLogin];
            }
           
        }
        [self loadAppstoreInfo];
    } failure:^(NSError * _Nullable error) {
        
    }];
    
}
-(void)loadAppstoreInfo{
    [CXDNetHelp getRequestWithURLString:[NSString stringWithFormat:@"http://itunes.apple.com/lookup?id=%@", @"1399320717"] parameters:nil success:^(id  _Nullable responseObject) {
    
        NSArray *infoArray = [responseObject objectForKey:@"results"];
        if (infoArray && infoArray.count > 0) {
            NSDictionary *releaseInfo = [infoArray objectAtIndex:0];
            //描述
            self.versionInfo.releaseNote = releaseInfo[@"releaseNotes"];
            self.versionInfo.version = releaseInfo[@"version"];
            self.versionInfo.URI = releaseInfo[@"trackViewUrl"];
            
            if (self.needsForceUpdate) {
                //强制更新 发送通知   通知接受对象可以更加自己项目情况来定
                [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAppShouldUpdate object:@{@"URI":self.versionInfo.URI}];
                return;
            }
            //是否忽略这个版本
            self.versionIgnored = ([self.versionInfo.version isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:UDkUpdateIgnoredVersion]]);
            //要判断这里忽略过的版本是不是更新了 和本地版本号已经一样了
            if ([VERSION isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:UDkUpdateIgnoredVersion]]) {
                self.versionIgnored = NO;
                [[NSUserDefaults standardUserDefaults]removeObjectForKey:UDkUpdateIgnoredVersion];
            }
            self.hasNewVersion = ([VERSION compare:self.versionInfo.version options:NSNumericSearch] == NSOrderedAscending);
            
            if (self.versionIgnored) {
                NSLog(@"忽略的版本");
                return;
            }
            if (self.hasNewVersion) {
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"新版本%@",self.versionInfo.version] message:[NSString stringWithFormat:@"%@",self.versionInfo.releaseNote] preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* cancel = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel
                                                               handler:^(UIAlertAction * action) {
                                                                   
                                                                   
                                                               }];
                UIAlertAction* updata = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDestructive
                                                               handler:^(UIAlertAction * action) {
                                                                   NSURL *url = [NSURL URLWithString:self.versionInfo.URI];
                                                                   if ([[UIApplication sharedApplication]canOpenURL:url]) {
                                                                       [[UIApplication sharedApplication] openURL:url];
                                                                   }
                                                               }];
                UIAlertAction* ignore = [UIAlertAction actionWithTitle:@"忽略此版本" style:UIAlertActionStyleDestructive
                                                               handler:^(UIAlertAction * action) {
                                                                   [self ignoreCurrentVersion];
                                                               }];
                [alert addAction:updata];
                [alert addAction:ignore];
                [alert addAction:cancel];
                [[AppDelegate shareAppDelegate].getCurrentUIVC  presentViewController:alert animated:YES completion:nil];
                
            }
            
        }

    } failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)cheackAppVersion{
    
}
- (void)checkAppVersionIsInitiative:(BOOL)flag{
    
}
- (void)ignoreCurrentVersion {
    
    [[NSUserDefaults standardUserDefaults] setObject:self.versionInfo.version forKey:UDkUpdateIgnoredVersion];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
@end

@implementation NRWAppInfoModel

@end
